package pl.us.ij.plugins.segmentation.commands.threshold;

import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import pl.us.ij.plugins.segmentation.infrastructure.Command;
import pl.us.ij.plugins.segmentation.infrastructure.exceptions.BreakCommandException;

/**
 * Created by IntelliJ IDEA.
 * User: Przemek
 * Date: 2010-01-02
 * Time: 21:25:39
 * To change this template use File | Settings | File Templates.
 */
public class GradientThresholdCommand extends Command {
//    @Override

    protected void processImage(FloatProcessor fp) throws BreakCommandException {

        int width = fp.getWidth();
        int height = fp.getHeight();

        ImageProcessor ip = fp;

        float[] pixels = (float[]) ip.getPixels();

        int threshold = findThreshold(width, height, pixels);

        OneLevelThresholdCommand.thresholdPixels(threshold, pixels, (float)ip.getMin(), (float)ip.getMax());
    }

    public static int findThreshold(int width, int height, float[] pixels) {
        float gX = 0;
        float gY = 0;
        float gMax = 0;
        float counter = 0;
        float denominator = 0;

        for (int y = 1; y < height - 1; y++) {
            int shift0 = (y - 1) * width;
            int shift1 = (y) * width;
            int shift2 = (y + 1) * width;
            int shiftD = y * width;
            for (int x = 1; x < width - 1; x++) {

                gX = Math.abs(pixels[shift1 + x + 1] - pixels[shift1 + x - 1]);
                gY = Math.abs(pixels[shift0 + x] - pixels[shift2 + x]);

                if (gX > gY)
                    gMax = gX;
                else
                    gMax = gY;

                counter += pixels[shift1 + x] * gMax;
                denominator += gMax;
            }
        }
        int threshold = (int) (counter / denominator);
        return threshold;
    }

//    @Override
    protected void process(FloatProcessor fp) throws BreakCommandException {

        processImage(fp);
    }
}
